package com.school.edupoint.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.model.StudentGift;
import com.school.edupoint.response.Result;
import com.school.edupoint.service.StudentGiftService;
import com.school.edupoint.vo.MessageVO;
import com.school.edupoint.websocket.MyTextWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
public class StudentGiftController {
    @Autowired
    private EduContext eduContext;
    @Autowired
    private StudentGiftService studentGiftService;


    /**
     * 查询单人兑换详情
     *
     * @param
     * @return
     */
    @PostMapping("/studentGift/info/getStudentGiftInfo")
    public Result<IPage<StudentGift>> getStudentGiftInfo(@RequestBody Map<String, Object> param) throws Exception {
        String title = (String) param.get("title");

        int pageNum = (int) param.get("pageNum");
        int pageSize = (int) param.get("pageSize");

        System.out.println("当前第" + pageNum + "页");
        System.out.println("一页" + pageSize + "条数据");
        IPage<StudentGift> giftIPage = studentGiftService.getStudentGiftInfo(title, pageNum, pageSize);
        return Result.success(giftIPage);
    }

    /**
     * 兑换分页
     *
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/studentGift/page")
    public Result<IPage<StudentGift>> getGiftPage(@RequestBody Map<String, Object> param) throws Exception {
        String title = (String) param.get("title");
        String studentName = (String) param.get("studentName");

        int pageNum = (int) param.get("pageNum");
        int pageSize = (int) param.get("pageSize");
        Integer status = (Integer) param.get("status");
        System.out.println("当前第" + pageNum + "页");
        System.out.println("一页" + pageSize + "条数据");
        IPage<StudentGift> giftIPage = studentGiftService.selectPage(title, pageNum, pageSize, status, studentName);
        System.out.println("活动分页数据为：" + giftIPage);
        return Result.success(giftIPage);
    }
////兑换状态（1已兑换未发货，2已发货,3已送达，4取消）
    /**
     * 兑换商品发货
     *
     * @param param
     * @return
     */
    @PostMapping("/studentGift/delivery")
    public Result<String> delivery(@RequestBody Map<String, Object> param) {
        Integer studentGiftId = (Integer) param.get("studentGiftId");
        System.out.println("发货接口前端传过来数据：" + studentGiftId);
        String result = studentGiftService.delivery(studentGiftId);

        // 如果发货成功，发送WebSocket通知给学生
        if ("已发货".equals(result)) {
            try {
                // 获取兑换记录信息
                StudentGift studentGift = studentGiftService.getById(studentGiftId);
                if (studentGift != null) {
                    MessageVO messageVO = new MessageVO();
                    messageVO.setUserId(studentGift.getStudentId().toString());
                    messageVO.setTitle("礼物发货通知");
                    messageVO.setContent("您的礼物《" + studentGift.getGiftName() + "》已发货，请注意查收！");
                    messageVO.setMessageType("GIFT_SHIPPED");
                    messageVO.setParam("{\"giftId\":" + studentGiftId + ",\"giftName\":\"" + studentGift.getGiftName() + "\"}");

                    // 发送给特定学生
                    MyTextWebSocketHandler.sendToUser(studentGift.getStudentId().toString(), messageVO);
                    System.out.println("已向学生发送礼物发货通知：学生ID " + studentGift.getStudentId() + "，礼物 " + studentGift.getGiftName());
                }
            } catch (Exception e) {
                System.err.println("发送WebSocket通知失败：" + e.getMessage());
                e.printStackTrace();
            }
        }

        return Result.success(result);
    }

    /**
     * 兑换商品已送达
     *
     * @param param
     * @return
     */
    @PostMapping("/studentGift/over")
    public Result<String> over(@RequestBody Map<String, Object> param) {
        Integer studentGiftId = (Integer) param.get("studentGiftId");
        System.out.println("已送达接口前端传过来数据：" + studentGiftId);
        String result = studentGiftService.over(studentGiftId);

        // 如果送达成功，发送WebSocket通知给学生
        if ("已送达".equals(result)) {
            try {
                // 获取兑换记录信息
                StudentGift studentGift = studentGiftService.getById(studentGiftId);
                if (studentGift != null) {
                    MessageVO messageVO = new MessageVO();
                    messageVO.setUserId(studentGift.getStudentId().toString());
                    messageVO.setTitle("礼物送达通知");
                    messageVO.setContent("您的礼物《" + studentGift.getGiftName() + "》已送达，请注意查收！");
                    messageVO.setMessageType("GIFT_DELIVERED");
                    messageVO.setParam("{\"giftId\":" + studentGiftId + ",\"giftName\":\"" + studentGift.getGiftName() + "\"}");

                    // 发送给特定学生
                    MyTextWebSocketHandler.sendToUser(studentGift.getStudentId().toString(), messageVO);
                    System.out.println("已向学生发送礼物送达通知：学生ID " + studentGift.getStudentId() + "，礼物 " + studentGift.getGiftName());
                }
            } catch (Exception e) {
                System.err.println("发送WebSocket通知失败：" + e.getMessage());
                e.printStackTrace();
            }
        }

        return Result.success(result);
    }

    /**
     * 取消送货
     */
    @PostMapping("/studentGift/cancel")
    public Result<String> cancel(@RequestBody Map<String, Object> param) {
        Integer studentGiftId = (Integer) param.get("studentGiftId");
        System.out.println("取消兑换接口前端传过来数据：" + studentGiftId);
        String result = studentGiftService.cancel(studentGiftId);

        // 如果取消成功，发送WebSocket通知给学生
        if ("已取消".equals(result)) {
            try {
                // 获取兑换记录信息
                StudentGift studentGift = studentGiftService.getById(studentGiftId);
                if (studentGift != null) {
                    MessageVO messageVO = new MessageVO();
                    messageVO.setUserId(studentGift.getStudentId().toString());
                    messageVO.setTitle("礼物取消通知");
                    messageVO.setContent("您的礼物《" + studentGift.getGiftName() + "》兑换已被取消");
                    messageVO.setMessageType("GIFT_CANCELLED");
                    messageVO.setParam("{\"giftId\":" + studentGiftId + ",\"giftName\":\"" + studentGift.getGiftName() + "\"}");

                    // 发送给特定学生
                    MyTextWebSocketHandler.sendToUser(studentGift.getStudentId().toString(), messageVO);
                    System.out.println("已向学生发送礼物取消通知：学生ID " + studentGift.getStudentId() + "，礼物 " + studentGift.getGiftName());
                    //通知管理员
                    MessageVO messageVO1 = new MessageVO();
                    messageVO1.setTitle("礼物取消兑换通知");
                    messageVO1.setContent("学生 " + studentGift.getStudentName() + " 的《" + studentGift.getGiftName() + "》兑换已取消");
                    messageVO1.setMessageType("GIFT_EXCHANGE");
                    messageVO1.setParam("{\"studentId\":" + studentGift.getStudentId() + ",\"studentName\":\"" + studentGift.getStudentName() + "\",\"giftId\":" + studentGift.getGiftId() + ",\"giftName\":\"" + studentGift.getGiftName() + "\"}");
                    // 向所有管理员发送通知
                    MyTextWebSocketHandler.broadcastToAllAdmins(messageVO1);
                    System.out.println("已向管理员发送礼物取消兑换通知：学生 " + studentGift.getStudentName() + "，礼物 " + studentGift.getGiftName());

                }
            } catch (Exception e) {
                System.err.println("发送WebSocket通知失败：" + e.getMessage());
                e.printStackTrace();
            }
        }

        return Result.success(result);
    }

}
